﻿using System.Security.Claims;
using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;

namespace Ids4.Server;

public class ProfileService : IProfileService
{
    /// <summary>
    /// 根据Id拿到用户所属角色，添加到Token中
    /// </summary>
    /// <param name="context"></param>
    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var user = UserData.GetListUsers().FirstOrDefault(p => p.Id == context.Subject.GetSubjectId());

        // 存在多个权限时
        var roleArr = user.Role.Split(",");

        var claims = new List<Claim>();
        foreach (var item in roleArr)
        {
            claims.Add(new Claim(JwtClaimTypes.Role, item));
        }

        context.IssuedClaims = claims;
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        context.IsActive = true;
    }
}